// 用于手动下载Electron二进制文件的脚本
const fs = require('fs');
const path = require('path');
const https = require('https');
const { exec } = require('child_process');

// 从package.json获取实际Electron版本
const packageJson = require('./package.json');
const electronVersion = packageJson.devDependencies.electron.replace('^', '');
console.log(`从package.json中检测到Electron版本: ${electronVersion}`);

// 设置下载参数
const platform = process.platform;
const arch = process.arch === 'x64' ? 'x64' : 'ia32';
const baseUrl = 'https://npmmirror.com/mirrors/electron';
const zipFileName = `electron-v${electronVersion}-${platform === 'win32' ? 'win32' : platform}-${arch}.zip`;
const downloadUrl = `${baseUrl}/${electronVersion}/${zipFileName}`;

// 创建目录
const electronCacheDir = path.join(__dirname, '.electron-download', electronVersion);
if (!fs.existsSync(electronCacheDir)) {
  fs.mkdirSync(electronCacheDir, { recursive: true });
}

const outputPath = path.join(electronCacheDir, zipFileName);
console.log(`下载URL: ${downloadUrl}`);
console.log(`保存路径: ${outputPath}`);

// 使用https模块下载文件
const file = fs.createWriteStream(outputPath);
https.get(downloadUrl, response => {
  if (response.statusCode === 200) {
    response.pipe(file);

    // 显示下载进度
    let downloadedBytes = 0;
    const totalBytes = parseInt(response.headers['content-length'], 10);

    response.on('data', chunk => {
      downloadedBytes += chunk.length;
      const progress = (downloadedBytes / totalBytes * 100).toFixed(2);
      process.stdout.write(`\r下载进度: ${progress}% (${downloadedBytes}/${totalBytes} 字节)`);
    });

    file.on('finish', () => {
      file.close();
      console.log('\n下载完成!');
      console.log('现在您可以运行 npm run build:offline 进行离线打包');

      // 可选: 验证Electron二进制文件的完整性
      console.log('验证下载文件...');
      const fileStats = fs.statSync(outputPath);
      console.log(`文件大小: ${(fileStats.size / 1024 / 1024).toFixed(2)} MB`);

      if (platform === 'win32') {
        // 在Windows上检查zip文件
        exec(`powershell -command "Get-FileHash '${outputPath}' -Algorithm SHA256 | Select-Object Hash"`, (error, stdout) => {
          if (error) {
            console.error(`检查文件哈希出错: ${error}`);
            return;
          }
          const hashMatch = stdout.match(/[A-F0-9]{64}/);
          if (hashMatch) {
            console.log(`文件哈希: ${hashMatch[0]}`);
          }
        });
      }
    });
  } else {
    fs.unlinkSync(outputPath);
    console.error(`下载失败，HTTP状态码: ${response.statusCode}`);
    console.error(`请尝试直接从浏览器访问: ${downloadUrl}`);
  }
}).on('error', err => {
  fs.unlinkSync(outputPath);
  console.error(`下载出错: ${err.message}`);
}); 